package com.jckl.foodathon.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.restlet.engine.util.Base64;

import com.jckl.foodathon.model.Blogger;
import com.jckl.foodathon.model.Store;

public class StoreDAO {
	
	public boolean newStore(Store store){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean createdSuccess = false;
		
		try{
			pm.makePersistent(store);
			createdSuccess = true;
		}finally{
			pm.close();
		}
		return createdSuccess;
	}
	
	public List<Store> getStoresByLatest(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Store.class);
		
		List<Store> stores = new ArrayList<Store>();

		try{
			query.setOrdering("updatedDate desc");
			stores = (List<Store>) query.execute();
			
		}finally{
			pm.close();
			query.closeAll();
		}
		return stores;
	}
	
	public List<Store> getStores(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Store.class);
		
		List<Store> stores = new ArrayList<Store>();
		List<Store> encodedStores = new ArrayList<Store>();

		try{
			query.setOrdering("name asc");
			stores = (List<Store>) query.execute();
			
		}finally{
			pm.close();
			query.closeAll();
		}
		
		for (Store store : stores) {
			if(store.getImage() != null){
				store.setEncodedImage(Base64.encode(store.getImage().getBytes(), false));
				store.setImage(null);
			}
			encodedStores.add(store);
		}
		
		return encodedStores;
	}
	
	public Store getStoreByName(String storeName){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Store.class);
		
		List<Store> stores = null;
		Store store = null;

		try{
			query.setFilter("name == storeName");
			query.declareParameters("String storeName");
			stores = (List<Store>) query.execute(storeName);
			
			if(stores.size()>0){
				store = stores.get(0);
			}
		}catch (Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
			query.closeAll();
		}
		return store;
	}
	
	public Store getStoreByName(String storeName, Query query){
		if(storeName == null){
			return null;
		}
		
		List<Store> stores = null;
		Store store = null;

		try{
			query.setFilter("name == storeName");
			query.declareParameters("String storeName");
			stores = (List<Store>) query.execute(storeName);
			
			if(stores.size()>0){
				store = stores.get(0);
			}
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return store;
	}
	
	public boolean updateStore (Store store){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean updatedSuccess = false;
		
		try{
			pm.makePersistent(store);
			updatedSuccess = true;
		}finally{
			pm.close();
		}
		return updatedSuccess;
	}
}
